package com.ghsc.ghxc.jsb.ui.integral.activity

import android.app.Activity
import android.content.Intent
import android.content.pm.ActivityInfo
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import androidx.recyclerview.widget.GridLayoutManager
import com.cn.appcore.base.BaseVMActivity
import com.cn.appcore.event.RxBus
import com.cn.appcore.event.RxBusBean
import com.cn.appcore.event.SchedulerTransformer
import com.cn.appcore.ext.getCompatColor
import com.cn.appcore.ext.gone
import com.cn.appcore.ext.loge
import com.cn.appcore.ext.setSingleClickListener
import com.cn.appcore.ext.showToast
import com.cn.appcore.ext.startKtxActivity
import com.cn.appcore.ext.visible
import com.cn.appcore.utils.GlideEngine
import com.cn.appcore.utils.GsonUtil
import com.cn.appcore.utils.TimeUtils
import com.ghsc.ghxc.jsb.R
import com.ghsc.ghxc.jsb.config.CustKey
import com.ghsc.ghxc.jsb.config.LoginHelper
import com.ghsc.ghxc.jsb.config.UserManager
import com.ghsc.ghxc.jsb.databinding.ActivityReleaseCommodityBinding
import com.ghsc.ghxc.jsb.ext.intentExtras
import com.ghsc.ghxc.jsb.ui.integral.IntegralSupermarketViewModel
import com.ghsc.ghxc.jsb.ui.integral.adapter.GridImagePicAdapter
import com.ghsc.ghxc.jsb.ui.integral.bean.Category
import com.ghsc.ghxc.jsb.ui.integral.bean.IntegralSkuBean
import com.ghsc.ghxc.jsb.ui.integral.view.IntegralTypeListPopupView
import com.ghsc.ghxc.jsb.ui.message.view.PayPwdPopViiew
import com.ghsc.ghxc.jsb.ui.my.activity.AddressActivity
import com.ghsc.ghxc.jsb.ui.my.bean.AddressDetailBean
import com.ghsc.ghxc.jsb.utils.OSSUtil
import com.ghsc.ghxc.jsb.utils.OssUpUtils
import com.ghsc.ghxc.jsb.utils.StringUtil
import com.ghsc.ghxc.jsb.view.ConfirmCancelPopViiew
import com.luck.picture.lib.PictureSelector
import com.luck.picture.lib.config.PictureConfig
import com.luck.picture.lib.config.PictureMimeType
import com.luck.picture.lib.entity.LocalMedia
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.enums.PopupAnimation
import rx.functions.Action1

/**
 * 项目：GuoHuaJsb
 * 包名：com.ghsc.ghxc.jsb.ui.integral.activity
 * 类名：ReleaseCommodityActivity
 * 创建时间：2024/5/20 11:41
 * 创建人 @author： xiaolin
 * 描述 ：Todo... 发布商品
 */
class ReleaseCommodityActivity : BaseVMActivity<IntegralSupermarketViewModel, ActivityReleaseCommodityBinding>()  {
    override fun attachLayoutRes(): Int {
        return R.layout.activity_release_commodity
    }

    override fun attachVMClass(): Class<IntegralSupermarketViewModel>? {
       return IntegralSupermarketViewModel::class.java
    }


    //图片 视频 悬着
    private var selectList: MutableList<LocalMedia> = ArrayList()
    private val maxSelectNum = 6
    private var adapter: GridImagePicAdapter? = null
    private var themeId = 0



    //上传的图片数组
    var temListPicUrl: MutableList<String> = ArrayList()
    //详情里面的图片
    var mListPic : MutableList<String>  = mutableListOf()


    //分类选择
    var category : String?= null




    var bundle:Bundle?= null
    var pid :String =""

    override fun initBar() {
        super.initBar()
        mImmersionBar!!.statusBarDarkFont(true).init()
    }


    //积分模块的个人信息缓存
    val userInfo=UserManager.getIntegralUserInfo()
    override fun initView() {
        bundle=intent.extras
        if (bundle!=null){
            pid= bundle!!.getString("pid","")
        }

        binding.bar.topTitle.text="发布商品"
        binding.bar.topLeftView.setSingleClickListener {
            hideKeyboard(binding.etName)
            finish()
        }
        themeId = R.style.picture_default_style
        binding.rvListPic.layoutManager = GridLayoutManager(this, 3)
        adapter = GridImagePicAdapter()
        adapter?.GridImagePicAdapter(this, onAddPicClickListener)
        adapter?.setList(selectList)
        adapter?.setSelectMax(maxSelectNum)
        binding.rvListPic.adapter = adapter
        adapter?.setOnItemClickListener(object : GridImagePicAdapter.OnItemClickListener {
            override fun onItemClick(position: Int, v: View?) {
                if (selectList.size > 0) {
                    val media = selectList[position]
                    val mimeType = media.mimeType
                    val mediaType = PictureMimeType.getMimeType(mimeType)
                    when (mediaType) {
                        PictureConfig.TYPE_IMAGE ->                         // 预览视频
                            PictureSelector.create(this@ReleaseCommodityActivity)
                                .themeStyle(R.style.picture_default_style) // xml设置主题
                                //.setPictureWindowAnimationStyle(animationStyle)// 自定义页面启动动画
                                .setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED) // 设置相册Activity方向，不设置默认使用系统
                                .isNotPreviewDownload(true) // 预览图片长按是否可以下载
                                //.bindCustomPlayVideoCallback(new MyVideoSelectedPlayCallback(getContext()))// 自定义播放回调控制，用户可以使用自己的视频播放界面
                                .imageEngine(GlideEngine.createGlideEngine()) // 外部传入图片加载引擎，必传项
                                .openExternalPreview(position, selectList)
                        else ->  {

                        }
                    }
                }
            }
        })
        if (!TextUtils.isEmpty(pid)){
            binding.bar.topTitle.text="修改商品"
            binding.llSpec.visible()
            getDetailsData(pid)
            getSkuData(pid)
        }


        rxBusSubscription = RxBus.getDefault().toObservable(RxBusBean::class.java)
            .compose(SchedulerTransformer<RxBusBean>())
            .subscribe(Action1<RxBusBean> { rxBusBean ->
                if (rxBusBean.id == 204 && rxBusBean.sign == 204) {
                    // 删除图片后才传值
                    val index = rxBusBean.anyBean
                    //                            LoggerUtils.e("删除了图片收到之前集合：" + strPics.size() + "str：" + strPics.toString());
//                            LoggerUtils.e("删除了图片收到：" + index);
                    if (temListPicUrl.size > 0)
                        temListPicUrl.removeAt(index as Int) // 删除临时集合里面的
                    if (mListPic.size > 0)
                        mListPic.removeAt(index as Int) // 删除要上传id集合里面的
                    //                            LoggerUtils.e("删除了图片收到之后集合：" + strPics.size() + "str：" + strPics.toString());
                }
            })


    }

    private val onAddPicClickListener: GridImagePicAdapter.onAddPicClickListener = object :
        GridImagePicAdapter.onAddPicClickListener {
        override fun onAddPicClick() {
            hideKeyboard(binding.etName)
            // 进入相册 以下是例子：不需要的api可以不写
            PictureSelector.create(this@ReleaseCommodityActivity)
                .openGallery(PictureMimeType.ofImage()) // 全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                .loadImageEngine(GlideEngine.createGlideEngine()) // 外部传入图片加载引擎，必传项
                .theme(themeId) // 主题样式设置 具体参考 values/styles   用法：R.style.picture.white.style v2.3.3后 建议使用setPictureStyle()动态方式
                .isWeChatStyle(false) // 是否开启微信图片选择风格
                .isWithVideoImage(false) // 图片和视频是否可以同选,只在ofAll模式下有效
                .maxSelectNum(maxSelectNum) // 最大图片选择数量
                .minSelectNum(1) // 最小选择数量
                .imageSpanCount(4) // 每行显示个数
                .isReturnEmpty(false) // 未选择数据时点击按钮是否可以返回
                .setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED) // 设置相册Activity方向，不设置默认使用系统
                .isOriginalImageControl(false) // 是否显示原图控制按钮，如果设置为true则用户可以自由选择是否使用原图，压缩、裁剪功能将会失效
                .selectionMode(PictureConfig.MULTIPLE) // 多选 or 单选
                .isSingleDirectReturn(false) // 单选模式下是否直接返回，PictureConfig.SINGLE模式下有效
                .previewImage(true) // 是否可预览图片
                .previewVideo(true) // 是否可预览视频
                .enablePreviewAudio(false) // 是否可播放音频
                .isCamera(true) // 是否显示拍照按钮
                .isZoomAnim(true) // 图片列表点击 缩放效果 默认true
                .enableCrop(false) // 是否裁剪
                .compress(true) // 是否压缩
                .compressQuality(80) // 图片压缩后输出质量 0~ 100
                .synOrAsy(true) //同步false或异步true 压缩 默认同步
                .openClickSound(true) // 是否开启点击声音
                .selectionMedia(selectList) // 是否传入已选图片
                .cutOutQuality(90) // 裁剪输出质量 默认100
                .minimumCompressSize(100) // 小于100kb的图片不压缩
                .forResult(PictureConfig.CHOOSE_REQUEST) //
        }
    }
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when (resultCode) {
            Activity.RESULT_OK -> when (requestCode) {
                PictureConfig.CHOOSE_REQUEST -> {
                    selectList = PictureSelector.obtainMultipleResult(data)
                    adapter!!.setList(selectList)
                    adapter!!.notifyDataSetChanged()
                    temListPicUrl.clear()
                    for (media in selectList) {
                        if (!TextUtils.isEmpty(media.compressPath))
                            temListPicUrl.add(media.compressPath)
                    }
                }
            }
        }
    }


    override fun initClickListener() {
        super.initClickListener()
        binding.llBtntype.setSingleClickListener {
            //分类
            mViewModel.onCatecfgMethod("")
        }
        binding.llSpec.setSingleClickListener {
            //选择规格
            if(!TextUtils.isEmpty(pid)){
                startKtxActivity<SpecUpActivity>(
                    values = arrayListOf(
                        "pid" to pid
                    )
                )
            }
        }
        binding.btnPut.setSingleClickListener{



            if (TextUtils.isEmpty(binding.etName.text.toString().trim())){
                showToast("请输入产品名称")
                return@setSingleClickListener
            }
            if (TextUtils.isEmpty(binding.etType.text.toString().trim())){
                showToast("请选择产品类型")
                return@setSingleClickListener
            }
            if (TextUtils.isEmpty(binding.etDescribe.text.toString().trim())){
                showToast("请输入产品描述")
                return@setSingleClickListener
            }
            if (selectList.size==0){
                showToast("请上传产品图片")
                return@setSingleClickListener
            }

            if(TextUtils.isEmpty(pid)){
                val tips =userInfo?.tips+"\n"+"积分余额:"+userInfo?.jifen
                XPopup.Builder(this@ReleaseCommodityActivity)
                    .popupAnimation(PopupAnimation.ScaleAlphaFromCenter  )
                    .customHostLifecycle(lifecycle)
                    .navigationBarColor(getCompatColor(R.color.bg_dark_color))
                    .asCustom(
                        ConfirmCancelPopViiew(this@ReleaseCommodityActivity,"提示",tips,
                            btnConfirm={
                                XPopup.Builder(this@ReleaseCommodityActivity)
                                    .popupAnimation(PopupAnimation.ScaleAlphaFromCenter  )
                                    .customHostLifecycle(lifecycle)
                                    .autoOpenSoftInput(true)
                                    .moveUpToKeyboard(true)
                                    .dismissOnTouchOutside(false)
                                    .navigationBarColor(getCompatColor(R.color.bg_dark_color))
                                    .asCustom(
                                        PayPwdPopViiew(this@ReleaseCommodityActivity,object :
                                            PayPwdPopViiew.SublickListener{
                                            override fun onAdopt( pwdStr: String) {
                                                //送礼物
                                                setPutCommodityData(pwdStr)
                                            }
                                        })
                                    )
                                    .show()




                            },
                            btnCancel={
                            },)
                    )
                    .show()

            }else{
                setPutCommodityData("")
            }




        }
    }

    ///提交商品
    fun  setPutCommodityData(pwd:String){
        val list = arrayListOf<String>()
        temListPicUrl.forEach {
            list.add(it)
        }
        loge("上传的图片===:${list.size}")
        showLoading()
        if(list.size>0){
            OSSUtil.upLoadMultiFiles(this,list,CustKey.IMG_URL_COMMODITY, uploadMultiFilesCallback = object :
                OSSUtil.UploadMultiFilesCallback{
                override fun onUploadSuccess(urlList: ArrayList<String>) {
                    dismissLoading()
                    if(mListPic.size>0)
                        mListPic.forEach {
                            urlList.add(it)
                        }
                    val map: HashMap<String, Any> = HashMap()
                    map["pid"] = pid
                    map["title"] = binding.etName.text.toString()
                    map["images"] =StringUtil.convertListToString(urlList).toString()
                    map["memo"] = binding.etDescribe.text.toString()
                    map["category"] = binding.etType.text.toString()
                    map["paypassword"] = pwd
                    map["reason"] = ""
                    GsonUtil.mapToJsonStrObjEncryption(map)?.let { it1 -> mViewModel.onSubmitGoodsMethod(it1) }
                }
                override fun onUploadFailure() {
                    dismissLoading()
                }
            })
        }else{
            val map: HashMap<String, Any> = HashMap()
            map["pid"] = pid
            map["title"] = binding.etName.text.toString()
            map["images"] =StringUtil.convertListToString(mListPic).toString()
            map["memo"] = binding.etDescribe.text.toString()
            map["category"] = binding.etType.text.toString()
            map["paypassword"] = pwd
            map["reason"] = ""
            GsonUtil.mapToJsonStrObjEncryption(map)?.let { it1 -> mViewModel.onSubmitGoodsMethod(it1) }
        }

    }

    //商品详情
     fun getDetailsData(pid:String) {
        val map: HashMap<String, Any> = HashMap()
        map["pid"] =pid
        GsonUtil.mapToJsonStrObjEncryption(map)?.let { it1 -> mViewModel.ontGoodsDetailDataMethod(it1) }
    }
    //获取规格
    fun getSkuData(pid:String){
        //商品规格
        val map: HashMap<String, Any> = HashMap()
        map["pid"] = pid
        GsonUtil.mapToJsonStrObjEncryption(map)?.let { it1 -> mViewModel.onSkuDetailMethod(it1) }
    }

    override fun onResume() {
        super.onResume()
        if (!TextUtils.isEmpty(pid)){
            getSkuData(pid)
        }
    }

    override fun initRequestObserver() {
        super.initRequestObserver()
        mViewModel.apply {
            errorMsg.observe(this@ReleaseCommodityActivity) {
                dismissLoading()
                showToast(it)
            }
            againLoginMsg.observe(this@ReleaseCommodityActivity) {
                dismissLoading()
                showToast(CustKey.IN_AGAIN_MSG)
                LoginHelper.startLoginPage()

            }
            onCatecfgData.observe(this@ReleaseCommodityActivity) {
               //分类
                if (it.data.data.category.isNotEmpty())
                    if (!TextUtils.isEmpty(category))
                        for ( i in it.data.data.category.indices)
                            it.data.data.category[i].isSelect = it.data.data.category[i].catename ==category
                XPopup.Builder(this@ReleaseCommodityActivity)
                    .popupAnimation(PopupAnimation.ScaleAlphaFromCenter  )
                    .customHostLifecycle(lifecycle)
                    .dismissOnTouchOutside(true)
                    .navigationBarColor(getCompatColor(R.color.bg_dark_color))
                    .asCustom(
                        IntegralTypeListPopupView(this@ReleaseCommodityActivity,
                            it.data.data.category
                        ) {
                            loge("选择的是：${it.catename}")
                            category = it.catename
                            binding.etType.text = category
                        }
                    )
                    .show()
            }

            onSubmitGoodsData.observe(this@ReleaseCommodityActivity) {
                //发布商品
                dismissLoading()
                showToast("提交成功")
                binding.bar.topTitle.text="修改商品"
                pid=it.data.data.pid
                getDetailsData(pid)
                getSkuData(pid)
            }
            ontGoodsDetailData.observe(this@ReleaseCommodityActivity){
                //商品详情
                binding.etName.setText(it.data.data.title)
                binding.etType.setText(it.data.data.category)
                category=it.data.data.category
                binding.etDescribe.setText(it.data.data.memo)

                selectList.clear()
                mListPic.clear()
                if(!TextUtils.isEmpty(it.data.data.images)){
                    mListPic = it.data.data.images.split(",").toMutableList()
                    for (i in mListPic.indices){
                        var  localMedia = LocalMedia()
                        localMedia.path = mListPic[i]
                        selectList.add(localMedia)
                    }
                    adapter!!.setList(selectList)
                    adapter!!.notifyDataSetChanged()
                }
            }
            onSkuDetailData.observe(this@ReleaseCommodityActivity){
                //商品规格
                binding.llSpec.visible()
                if(it.data.list.isNotEmpty()){
                    var list : MutableList<String> = ArrayList()
                    for (i in it.data.list.indices)
                        list.add(it.data.list[i].skuname)
                    binding.tvSku.text=StringUtil.convertListToString(list).toString()
                }
            }
        }
    }
}